package com.ydlclass.discovery.impl;

import com.ydlclass.Constant;
import com.ydlclass.ServiceConfig;
import com.ydlclass.discovery.AbstractRegistry;
import com.ydlclass.utils.NetUtils;
import com.ydlclass.utils.zookeeper.ZookeeperNode;
import com.ydlclass.utils.zookeeper.ZookeeperUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * nacos注册中心
 * @Author duWenJian
 * @Date 2024/2/17 13:07
 * @Version 1.0
 */
@Slf4j
public class NacosRegistry extends AbstractRegistry {

    // todo
    private int port = 8088;
    private ZooKeeper zooKeeper ;

    public NacosRegistry() {
        this.zooKeeper = ZookeeperUtils.createZookeeper();
    }

    public NacosRegistry(String connectString, int timeOut) {
        this.zooKeeper = ZookeeperUtils.createZookeeper(connectString,timeOut);
    }

    @Override
    public void register(ServiceConfig<?> service) {
        // 服务名称的节点 /yrpc-metadata/providers/service.getInterface(接口名称)
        String parentNode = Constant.BASE_PROVIDERS_PATH + "/" + service.getInterface().getName();
        if (!ZookeeperUtils.exists(zooKeeper,parentNode,null)) {
            ZookeeperNode zookeeperNode = new ZookeeperNode(parentNode, null);
            // 不存在新建节点
            ZookeeperUtils.createNode(zooKeeper,zookeeperNode,null, CreateMode.PERSISTENT);
        }

        // 创建的临时节点,ip:port,
        // 服务提供方那个的端口一般是自己设定的，我们还需要一个获取ip的方法
        // ip我们通常是需要一个局域网ip，不是127.0.0.1,也不是ipv6
        // 192.168.26.1

        String node  = parentNode + "/" + NetUtils.getIp() + ":" + port;
        if (!ZookeeperUtils.exists(zooKeeper,node,null)) {
            ZookeeperNode zookeeperNode = new ZookeeperNode(node, null);
            // 不存在新建节点,创建一个临时节点
            ZookeeperUtils.createNode(zooKeeper,zookeeperNode,null, CreateMode.EPHEMERAL);
        }

        if (log.isDebugEnabled()) {
            log.debug("服务:{}已经被注册", service.getInterface().getName());
        }
    }

    @Override
    public List<InetSocketAddress> lookup(String serviceName ,String group) {
        return null;
    }
}
